<?php

class Request_Api_Request
{
	/**
	 * @var array
	 */
	protected $_types = NULL;

	/**
	 * @return array
	 */
	function _loadTypeSpecs()
	{
		$data = array();

		$table = Nuo::getTable('request/type');
		$select = $table -> select();
		$rows = $table -> fetchAll($select);
		foreach ($rows as $row)
		{
			$data[$row -> getId()] = $row -> toArray();
		}

		$this -> _types = $data;
	}

	/**
	 * @param string $actionType
	 * @return array|NULL
	 */
	function getTypeSpec($type)
	{
		if (NULL == $this -> _types)
		{
			$this -> _loadTypeSpecs();
		}

		if (isset($this -> _types[$type]))
		{
			return $this -> _types[$type];
		}

		return NULL;
	}

	/**
	 * @param Model $receiver
	 * @param Model $poster
	 * @param Model $typeId
	 * @param string $message
	 * @param Model $object
	 * @return bool
	 */
	function addRequest($poster, $receiver, $object, $typeId, $message = '', $extra = '')
	{
		if (!$poster)
		{
			return NULL;
		}

		if (!$receiver)
		{
			return NULL;
		}

		$resource = Nuo::getTable('request') -> fetchNew();

		$resource -> poster_id = $poster -> getItemId();
		$resource -> type_id = $typeId;
		$resource -> message = (string)$message;
		$resource -> created_at = time();
		$resource -> receiver_id = $receiver -> getItemId();

		if (is_object($object))
		{
			$resource -> object_id = $object -> getItemId();
		}

		$resource -> save();

		return $resource;
	}

}
